var fs = require('fs');
var Q = require('q');

var write2Json = function (language, path, json, type) {
  console.log('准备写入文件');
  if (!path) {
    path = './';
  } else if (!path.endsWith('/')) {
    path += '/';
  }
  json = JSON.stringify(json);
  if (type === undefined) {
    type = 'json';
  } else if (type === 'js') {
    json = '[' + json + ']';//单独js文件会报错，需要放到数组里
  }
  console.log(path + language + '.' + type);
  return Q.nfcall(fs.writeFile, path + language + '.' + type, json);
};

module.exports = function (path, language, dest, type) {
  return Q.nfcall(fs.readFile, path).then(function (data) {
    data = JSON.parse(data);
    var json = {};
    data.map(function (obj) {
      // console.log(obj);
      if (language === 'zh') {
        json[obj['code']] = obj['lanZhc'];
      } else {
        json[obj['code']] = obj['lanEn'];
      }
    });
    // console.log(json);
    return json;
  }, function (err) {
    console.error(err);
  }).then(function (json) {
    return write2Json(language, dest, json, type);
  });
};
